<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/12/22
 * Time: 9:25
 */

namespace app\api\controller;

use think\Db;

class Draw extends Base
{
    /**
     * 抽奖
     * @return \think\response\Json
     * userid     用户ID
     */
    public function decTimes(){
        header("Access-Control-Allow-Origin: *");
        $userid_rypt = input('userid');
        $userid = openssl_decrypt(hex2bin($userid_rypt), 'AES-128-ECB', $this->aeskey, OPENSSL_RAW_DATA);
        $userid = explode('|', rtrim($userid, '|'));
        $userid = $userid[0];
        
        // 判断该用户的抽奖次数
        $user = Db::table('up_u_user')->where('user_id', $userid)->field('user_draw_times')->find();
        if($user){
            if($user['user_draw_times'] > 0){
                Db::startTrans();
                try{
                    // 抽奖明细表
                    $info = [
                        'info_user_id' => $userid,
                        'info_draw_times' => 1,
                        'info_times_desc' => '抽奖',
                        'info_times_type' => 2,
                        'info_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_draw_info')->insert($info);
                    // 抽奖次数-1
                    Db::table('up_u_user')->where('user_id', $userid)->setDec('user_draw_times');
            
                    Db::commit();
                    return json(['status' => 200, 'msg' => true]);
                }catch(\Exception $e){
                    Db::rollback();
                    return json(['status' => 0, 'msg' => $e->getMessage()]);
                }
            }else{
                return json(['status' => 0, 'msg' => '抽奖次数不足']);
            }
        }else{
            return json(['status' => 0, 'msg' => '用户不存在']);
        }
    }
}